<template>
  <div class="calendar-container">
    <div class="left">
      <div class="small-calendar">
        <SmallCalendar />
      </div>
      <div class="calendar-add">
        <div class="add-top">
          <p>日历</p>
          <el-icon ref="buttonRef" @click="openPopover">
            <Plus />
          </el-icon>
          <el-popover :virtual-ref="buttonRef" trigger="click" virtual-triggering placement="right" ref="popoverRef"
            popper-class="calendar-popover">
            <div class="searchVal">
              <el-input size="small" v-model="searchValue" placeholder="搜索日历" clearable />
            </div>
            <div class="calendar-list">
              <div class="calendar-item" v-for="(item, index) in calendarList" :key="index" @click="itemClick(item)">
                <div class="item-box">
                  <div class="box-left">
                    <el-icon>
                      <Calendar />
                    </el-icon>
                    <div>{{ item.scheduleName }}</div>
                  </div>
                  <div class="box-right" v-if="item.check == 'true'">
                    <el-icon color="#409EFF">
                      <Check />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
            <div class="add-btn" @click="openAddDia">
              <el-icon size="14" style="margin-right: 5px;margin-top: 2px;">
                <Plus />
              </el-icon>
              <div>新建日历</div>
            </div>
          </el-popover>
        </div>
        <div class="calendarItem_body">
          <!-- 全部工作 -->
          <div class="taskItem" :class="{ 'selected-bg': selectedFixedTask === 'allSchedule' }"
            @click="fixedTaskClick('allSchedule')">
            <div class="taskLeft">
              <!-- <i class="el-icon-s-operation" style="color: rgb(102, 152, 255);"></i> -->
              <el-icon color="rgb(102, 152, 255)">
                <Calendar />
              </el-icon>
              <span>全部工作</span>
            </div>
          </div>
          <!-- 参与日程 -->
          <div class="taskItem" :class="{ 'selected-bg': selectedFixedTask === 'mySchedule' }"
            @click="fixedTaskClick('mySchedule')">
            <div class="taskLeft">

              <el-icon color="rgb(115, 216, 151)">
                <User />
              </el-icon>
              <span>参与日程</span>
            </div>
          </div>
          <!-- 工时任务 -->
          <div class="taskItem" :class="{ 'selected-bg': selectedFixedTask === 'myMission' }"
            @click="fixedTaskClick('myMission')">
            <div class="taskLeft">

              <el-icon color="rgb(0, 192, 238)">
                <Clock />
              </el-icon>
              <span>工时任务</span>
            </div>
          </div>

          <div class="taskItem" v-for="(item, index) in popoverData" :key="index" @click="taskClick(item)"
            :class="{ 'selected-bg': item.id == selectedTaskIndex }">
            <div class="taskLeft">
              <el-icon :color="item.scheduleColor">
                <Calendar />
              </el-icon>
              <span class="text_ellipsis">{{ item.scheduleName }}</span>
            </div>
            <div class="taskRight">
              <span @click.stop="starClick(item.id)">
                <el-tooltip class="item" effect="dark" :content="$t('calendar.unfollow')" placement="top">
                  <el-icon>
                    <StarFilled :size="14" color="rgb(247, 186, 42)" />
                  </el-icon>
                </el-tooltip>
              </span>
              <el-dropdown trigger="click" v-if="item.sysScheduleState == 'true'">
                <!-- <i class="el-icon-more-outline" style="color: #333;"></i> -->
                <el-icon color="#333" :size="14">
                  <More />
                </el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item class="custom-dropdown-item" :icon="Edit" @click.native="editClick(item)">{{
                      $t('calendar.edit') }}</el-dropdown-item>
                    <el-dropdown-item class="custom-dropdown-item" :icon="User" v-if="item.schedulePurview == 0"
                      @click.native="userClick(item)">
                      {{ $t('calendar.people') }}
                    </el-dropdown-item>
                    <el-dropdown-item class="custom-dropdown-item" :icon="Setting" @click.native="deleteCalendar(item)">
                      {{ $t('calendar.moreSet') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
      <div class="userItem">
        <div class="userItem_header">
          <p>成员</p>
          <el-icon @click="openUserDia">
            <Plus />
          </el-icon>
        </div>
        <el-checkbox v-if="peopleFollowList.length != 0" :indeterminate="isIndeterminatePeople" v-model="checkAllPeople"
          @change="handleCheckAllPeopleChange" style="margin-left: 10px;">
          {{ $t('calendar.checkAll') }}
        </el-checkbox>
        <div class="userItem_content">
          <div class="userItem_body" v-for="(item, index) in peopleFollowList" :key="index">
            <div class="userItem_body_box">
              <div class="taskLeft">
                <el-checkbox-group v-model="checkedPeopleList" @change="handleCheckedPeopleChange">
                  <el-checkbox :label="item.userId" :value="item.userId" :key="item.userId">{{ '' }}</el-checkbox>
                </el-checkbox-group>
                <div class="userName">
                  {{ item.nickName.slice(-2) }}
                </div>
                <span class="text_ellipsis">{{ item.nickName }}</span>
              </div>
              <div class="taskRight">
                <span @click="deletePeopleFollow(item)">
                  <el-tooltip class="item" effect="dark" :content="$t('calendar.unfollow')" placement="top">
                    <!-- <i class="el-icon-star-on" style="color: rgb(247, 186, 42);"></i> -->
                    <el-icon color="rgb(247, 186, 42)">
                      <StarFilled />
                    </el-icon>
                  </el-tooltip>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="resourceItem">
        <div class="resourceItem_header">
          <div>{{ $t('calendar.resource') }}</div>
          <el-tooltip :content="$t('calendar.addBtn')" placement="top">
            <el-icon ref="btnRef">
              <Plus />
            </el-icon>
          </el-tooltip>
          <!-- 全部资源 -->
          <el-popover style="display: none;" :virtual-ref="btnRef" placement="right" trigger="click" ref="resource"
            popper-class="resourPopover">
            <div class="popover-content">
              <div class="searchInput">
                <el-input :placeholder="$t('calendar.searchPlaceholder')" :prefix-icon="Search"
                  v-model="popoverSearchResource" @keyup.enter.native="searchResourceClick"></el-input>
              </div>
              <div class="lists">
                <div class="listsItem" v-for="(item, index) in ResourceAllList" :key="index"
                  @click="ResourceItemClick(item)">
                  <div class="leftItems">
                    <!-- <i class="el-icon-postcard" style="color:#6698ff"></i> -->
                    <el-icon color="#6698ff">
                      <Paperclip />
                    </el-icon>
                    <span class="Name_box">{{ item.resourceName }}</span>
                  </div>
                  <div class="rightItems" v-if="ResourceAllChecked(item)">
                    <!-- <i class="el-icon-check" style="color: #6698ff;"></i> -->
                    <el-icon color="#6698ff">
                      <Check />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </el-popover>
        </div>
        <!-- 个人关注的资源 -->
        <el-checkbox v-if="ResourceFollowList.length != 0" :indeterminate="isIndeterminateResource"
          v-model="checkAllResource" @change="handleCheckAllResourceChange" style="margin-left: 10px;">
          {{ $t('calendar.checkAll') }}
        </el-checkbox>
        <div class="resourceItem_content">
          <div class="resourceItem_body" v-for="(item, index) in ResourceFollowList" :key="index">
            <div class="taskItem">
              <div class="taskLeft">
                <el-checkbox-group v-model="checkedResourceList" @change="handleCheckedResourceChange">
                  <el-checkbox :label="item.resourceId" :value="item.resourceId" :key="item.resourceId">{{ ''
                  }}</el-checkbox>
                </el-checkbox-group>
                <i class="el-icon-postcard" style="color: rgb(102, 152, 255);"></i>
                <span>{{ item.resourceName }}</span>
              </div>
              <div class="taskRight">
                <span @click="ResourceStarClick(item)">
                  <el-tooltip class="item" effect="dark" :content="$t('calendar.unfollow')" placement="top">
                    <i class="el-icon-star-on" style="color: rgb(247, 186, 42);"></i>
                  </el-tooltip>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="right">
      <FullCalendar ref="fullCalendar" :options="calendarOptions" />
    </div>
    <!-- 选择成员 -->
    <SelectUser ref="selectUserRef" @sureDialogTransferClick="sureDialogTransferClick" />
    <!-- 新增日历 -->
    <AddCalendarDia ref="addCalendarDiaRef" @getData="getCalendarList" />
    <!-- 新增日程 -->
    <CreateDateEvent ref="createDateEventRef" :addDataTitle="diaType" @confirm="confirm_createSchedule" />
    <!-- 日程详情 -->
    <schedule-detail ref="ScheduleDetailRefs" @editScheduleClick="editScheduleClick_scheduleDetail"
      @refresh="ScheduleDetail_refresh"></schedule-detail>
    <el-dialog v-model="dialogVisible" title="快速创建" width="500">
      <div class="voice-item">
        <el-form ref="ruleFormRef" :model="formInline" :rules="rules" class="demo-form-inline" >
          <el-form-item label="日历" prop="scheduleId">
            <el-select v-model="formInline.scheduleId" placeholder="请选择日历">
              <el-option v-for="item in calendarList" :key="item.id" :label="item.scheduleName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="内容" prop="voiceText">
            <el-input ref="textInputRefs" class="input-box" v-model="formInline.voiceText" :autosize="{ minRows: 3 }"
              type="textarea" resize="none" placeholder="请输入内容或者点击语音录入"></el-input>
          </el-form-item>

        </el-form>

        <div class="btn_box">
          <div class="voice_box" title="点击语音输入">
            <img v-if="isSpeakType == 1" src="../../assets/images/chatgpt/mic.png" style="width:14px;" alt=""
              @click="startRecordAudio" />
            <div v-else-if="isSpeakType == 2">
              <div class="loaderRectangle" @click="stopRecordAudio">
                <div></div>
                <div></div>
                <div></div>
                <div></div>
                <div></div>
              </div>
            </div>
            <div v-else-if="isSpeakType == 3" class="SpeakType3">
              <icon-loading style="color: #e67e22;" />
              <span>转码中...</span>
            </div>
          </div>

        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button :loading="loading" type="primary" @click="sendText(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import FullCalendar from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import listPlugin from '@fullcalendar/list'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import SelectUser from '../components/select-user-check/select-user.vue'
import ScheduleDetail from './components/schedule-detail.vue'
import SmallCalendar from './components/small-calendar.vue'
import AddCalendarDia from './components/addCalendarDia.vue'
import CreateDateEvent from './components/createDateEvent.vue'
import { Edit, Setting, User, Search } from '@element-plus/icons-vue'
import moment from 'moment'
import Recorder from "js-audio-recorder"
import axios from "axios"
import tippy from 'tippy.js'
import "tippy.js/dist/tippy.css" //引入 tippy.js
import "tippy.js/themes/light.css" //引入主题
import "tippy.js/animations/scale.css"
import {
  sysScheduleGetPersonalAttention,
  sysScheduleAll,
  sysScheduleCancelAttentionDel,
  sysScheduleAttentionAdd,
  sysCalendarQueryInterval,
  apiSysScheduleAddAttention,
  apiSysScheduleGetAttentionAll,
  sysCalendarUpadate,
  apiSysResourceGetAllResource,
  apiSysScheduleAttentionShow,
  apiSysScheduleDeleteAttention,
  apiSysResourceAddResourceFollow,
  apiSysResourceGetResourceFollow,
  apiSysResourceResourceFollowShow,
  apiSysResourceDeleteResourceFollow,
  apiSysCalendarCreate,
  voiceAddSchedule
} from '@/api/calendar'

import type { ComponentSize, FormInstance, FormRules } from 'element-plus'


const ruleFormRef = ref<FormInstance>()
const fullscreenLoading = ref(false)
const loading = ref(false)
const formInline = reactive({
  voiceText: "",
  scheduleId: ''
})
const rules = reactive({
  voiceText: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ],
  scheduleId: [
    { required: true, message: '请选择日历', trigger: 'change' }
  ]
})
const isSpeakType = ref(1)
const dialogVisible = ref(false)
const { proxy } = getCurrentInstance() as any
const textInputRefs = ref<any>(null)

const recorder: any = new Recorder({
  sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
  sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
  numChannels: 1 // 声道，支持 1 或 2， 默认是1
  // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
})
const calendarOptions = reactive({
  height: '100%',  // 日历高度
  plugins: [dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin],  // 引入插件
  initialView: 'dayGridMonth',  // 初始视图
  locale: 'zh-cn',  // 语言
  dayMaxEvents: 5,// 最大事件数
  aspectRatio: 1.5, //日历单元格宽度与高度比，数值越大高度越小
  editable: true, // 是否可编辑
  droppable: true, // 是否可拖拽
  selectable: true, // 是否可选择
  displayEventTime: true, //是否显示日程时间，默认true
  displayEventEnd: true, //是否显示日程结束时间，默认false
  firstDay: 1, //设置一周中显示的第一天是哪天，周日是o，周一是1，类推
  // defaultAllDay: true, // 是否显示全天
  allDayText: '全天', // 全天事件文本
  nowIndicator: true,   // 显示当前时间线
  headerToolbar: {
    left: 'today addButton voiceButton',
    center: 'prev title next',
    right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
  },
  customButtons: {
    addButton: {
      text: '新建',
      click: function () {
        diaType.value = 'add'
        createDateEventRef.value.openDialog()
      }
    },
    // 语音识别
    voiceButton: {
      text: '语音新建',
      click: function () {
        voiceRecognition()
      }
    },
    prev: {
      text: '上一月',
      click: function () {
        fullCalendar.value.getApi().prev()
      }
    }, next: {
      text: '下一月',
      click: function () {
        fullCalendar.value.getApi().next()
      }
    },
    today: {
      text: '今天',
      click: function () {
        fullCalendar.value.getApi().today()
      }
    }
  },
  buttonText: {
    today: '今天',
    dayGridMonth: '月',
    timeGridWeek: '周',
    timeGridDay: '日',
    listMonth: '列表'
  },
  dateClick: function (info: any) {
    if (info.jsEvent.detail === 2) {
      diaType.value = 'add'
      nextTick(() => {
        createDateEventRef.value.openDialog(info)
      })
    }
  },
  datesSet: function (info: any) {
    currentView.value = info.view.type
  },
  eventDrop: function (info: any) {
    handleEventDrop(info)
  },
  eventClick: function (info: any) {
    eventClick(info)
  },
  eventMouseEnter: function (info: any) {
    eventMouseEnter(info)
  },

  events: [],
})


const selectedFixedTask = ref('allSchedule')
const currentView = ref("dayGridMonth")// 默认视图设置为月视界面
const selectUserRef = ref<any>(null)
const buttonRef = ref()
const searchValue = ref("")
const addCalendarDiaRef = ref<any>(null)
const createDateEventRef = ref<any>(null)
const popoverRef = ref<any>(null)
const diaType = ref('')
const selectedTaskIndex = ref(null)
const fullCalendar = ref<any>(null)
const isIndeterminatePeople = ref(false)
const checkAllPeople = ref(false)
const peopleFollowList = ref([])
const checkedPeopleList = ref([])
const ScheduleDetailRefs = ref<any>(null)
const route = useRoute()
const popoverSearchResource = ref("")
const ResourceAllList = ref([])
const ResourceFollowList = ref([])
const checkAllResource = ref(false)
const isIndeterminateResource = ref(false)
const checkedResourceList = ref([])
const ResourceAllIdsList = ref([])
const btnRef = ref<any>(null)
const tippyInstance = ref<any>(null)


const calendarList = ref([

])
const popoverData = ref([

])
const router = useRouter()

watch(
  () => route.query,
  async (to) => {
    if (to.scheduleId || to.type) {
      if (to.scheduleId) {
        selectedTaskIndex.value = to.scheduleId as string
        selectedFixedTask.value = null
      }
      if (to.type) {
        selectedTaskIndex.value = null
        selectedFixedTask.value = to.type as string
      }
      await nextTick()
      updateEventList()
      // checkedResourceList.value = []
      // isIndeterminateResource.value = false
      // checkAllResource.value = false
      // checkedPeopleList.value = []
      // isIndeterminatePeople.value = false
      // checkAllPeople.value = false
    }
  },
  { immediate: true, deep: true }
)

const voiceRecognition = async () => {
  dialogVisible.value = true
  formInline.voiceText = ""
  formInline.scheduleId = ""
  isSpeakType.value = 1
  getCalendarListAll()
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
}
/**语言录入----------------------------start */
// 开始录音
const startRecordAudio = () => {
  //@ts-ignore
  Recorder?.getPermission().then(
    () => {
      // console.log("开始录音");
      recorder.start() // 开始录音
      formInline.voiceText = ""
      formInline.scheduleId = ""
      isSpeakType.value = 2
    },
    (error: any) => {
      proxy.$modal.msgWarning('请先允许该网页使用麦克风并且确认插入麦克风')
      // console.log(`${error.name} : ${error.message}`);
    }
  )
}
// 停止录音
const stopRecordAudio = () => {
  recorder.stop()
  var wavBlob = recorder.getWAVBlob()
  isSpeakType.value = 3
  var formData = new FormData()
  const newbolb = new Blob([wavBlob], { type: 'audio/wav' })
  // //获取当时时间戳作为文件名
  const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
  formData.append("file", fileOfBlob)
  axios
    .post("/stt", formData, {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    })
    .then((res) => {
      console.log(res)
      formInline.voiceText = res.data
      isSpeakType.value = 1
      textInputRefs.value.focus()
    })
    .catch((err) => {
      isSpeakType.value = 1
      proxy.$modal.msgError("语音识别失败，请重试")

    })
}
/**语言录入----------------------------end */
const sendText = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const res = await voiceAddSchedule({
        voiceContent: formInline.voiceText,
      })
      if (res.code == 200) {
        const scheduleInfo = res.data
        voiceAddScheduleDetail(scheduleInfo)

      } else {
        loading.value = false
      }
    } else {
      loading.value = false
      console.log('error submit!', fields)
    }
  })
}

// 创建日程
const voiceAddScheduleDetail = async (scheduleInfo: any) => {
  const res = await apiSysCalendarCreate({
    label: scheduleInfo.label,
    scheduleId: formInline.scheduleId,
    startDate: scheduleInfo.startDate,
    endDate: scheduleInfo.endDate,
    workHours: scheduleInfo.workHours,
    content: formInline.voiceText,
    userIds:[]
  })
  if(res.code == 200){
    loading.value = false
    dialogVisible.value = false
    ElMessage.success("创建成功")
    updateEventList()
  }
}

const eventMouseEnter = (info: any) => {
  const formattedStart = moment(info.event.startStr).format('M月D日 HH:mm')
  const formattedEnd = moment(info.event.endStr).format('M月D日 HH:mm')
  tippyInstance.value = tippy(info.el, {
    appendTo: document.body,
    content: `<div style='display: flex;align-items: center;'>
          <div style="background-color: ${info.event.backgroundColor};width: 14px;height: 14px;border-radius: 10%;margin-right: 10px;"></div>
          <div style="color: #666666;font-size: 14px;">${info.event.title}</div>
        </div>
        <div style='color: #666666;font-size:12px'>${formattedStart} ~ ${formattedEnd}</div>
        <div style='display: flex;align-items: center;justify-content: space-between;margin-top: 10px;'>
        <div id='details' style='background-color: #6698ff;color: #fff;padding: 5px 10px;border-radius: 5px;cursor: pointer;font-size:12px'>查看详情</div>
           <div id='edit' style='color: #6698ff;cursor: pointer;font-size:12px'>编辑</div>
        </div>`,
    theme: "light",
    interactive: true,
    allowHTML: true,
    onShow(instance) {
      setTimeout(() => {
        const detailsButton = instance.popper.querySelector("#details")
        const editButton = instance.popper.querySelector("#edit")
        // 查看详情
        detailsButton.addEventListener("click", () => {
          eventClick(info)
          instance.hide()
        })

        // 编辑
        editButton.addEventListener("click", (val) => {
          // console.log(info.event.id)
          editScheduleClick_scheduleDetail(info.event)
          instance.hide()
        })

      }, 0)
    },
    onHidden(instance) {
      // 确保引用了正确的函数



      instance.destroy()

    }

  })
  if (info.view.type !== "dayGridMonth") {
    tippyInstance.value.destroy()
  }

  tippyInstance.value = null

}

const searchResourceClick = () => {
  getResourceAll()
}
const getResourceAll = async () => {
  const res = await apiSysResourceGetAllResource({
    resourceName: popoverSearchResource.value,
  })
  if (res.code == 200) {
    ResourceAllList.value = res.data.resource
    ResourceAllIdsList.value = res.data.resource_id
  }
}
const ResourceItemClick = async (item: any) => {
  if (ResourceAllChecked(item)) {
    ResourceStarClick(item)
  } else {
    let res = await apiSysResourceAddResourceFollow({
      resourceId: item.resourceId
    })
    if (res.code == 200) {
      ElMessage.success('添加成功')
      getResourceAll()
      getResourceFollow()
    }
  }
}
// 查询关注资源
const getResourceFollow = () => {
  apiSysResourceGetResourceFollow().then((res) => {
    if (res.code == 200) {
      ResourceFollowList.value = res.data
    }
  })
}
const ResourceAllChecked = (item: any) => {
  const index = ResourceAllIdsList.value.indexOf(item.resourceId)
  if (index !== -1) {
    return true
  } else {
    return false
  }
}
const handleCheckAllResourceChange = (val: any) => {
  let ids = ResourceFollowList.value.map((item) => item.resourceId)
  checkedResourceList.value = val ? ids : []
  isIndeterminateResource.value = false
  let path = `${route.path}?resource=1`
  router.push(path)
  getResourceSchedule()
}
const handleCheckedResourceChange = (value: any) => {
  let checkedCount = value.length
  checkAllResource.value = checkedCount === ResourceFollowList.value.length
  isIndeterminateResource.value = checkedCount > 0 && checkedCount < ResourceFollowList.value.length
  let path = `${route.path}?resource=1`
  router.push(path)
  getResourceSchedule()
}
const ResourceStarClick = (item: any) => {
  apiSysResourceDeleteResourceFollow({
    resourceId: item.resourceId
  }).then((res) => {
    if (res.code == 200) {
      ElMessage.success('取消成功')
      getResourceAll()
      getResourceFollow()

    }
  })
}
const getResourceSchedule = () => {
  // 成员勾选取消
  checkedPeopleList.value = []
  isIndeterminatePeople.value = false
  checkAllPeople.value = false

  //资源接口数据
  let { startDate, endDate } = calculateStartEndDates()
  if (checkedResourceList.value.length != 0) {
    // this.rightLoading = true
    apiSysResourceResourceFollowShow({
      startDate,
      endDate,
      resourceIds: checkedResourceList.value
    }).then((res) => {
      // this.rightLoading = false
      if (res.code == 200) {
        calendarOptions.events = res.data.map((item) => {
          return {
            title: item.label,
            start: item.startDate,
            end: item.endDate,
            color: item.calendarColor,
            content: item.content,
            id: item.id ? item.id : item.myTaskId,
            userList: item.userList,
            category: item.category,
            projectId: item.projectId
          }
        })
      }
    })
  } else {
    calendarOptions.events = []
  }
}
// 日程拖拽
const handleEventDrop = (info: any) => {
  let editStartData = info.event.startStr
    .replace("T", " ")
    .replace("Z", "")
    .replace(/\+\d{2}:\d{2}$/, "")
  let editEndData = info.event.endStr
    .replace("T", " ")
    .replace("Z", "")
    .replace(/\+\d{2}:\d{2}$/, "")
  let editData = {
    id: info.event._def.publicId,
    startDate: editStartData,
    endDate: editEndData,
    content: info.event.extendedProps.content,
    calendarType: info.event.extendedProps.calendarType,
    calendarPriority: info.event.extendedProps.calendarPriority,
    userIds: info.event.extendedProps.userList.map((user) => user.userId),
    label: info.event.title,
    calendarColor: info.event.backgroundColor
  }
  sysCalendarUpadate(editData).then((res) => {
    if (res.code == 200) {
      ElMessage.success('修改成功')
      updateEventList()
    }
  })
}
// 点击日程
const eventClick = (info: any) => {
  if (info.event.extendedProps.category == 'calendar') {
    ScheduleDetailRefs.value.getDetail(info.event.id)
  }
}

const openPopover = () => {
  unref(popoverRef).popperRef?.delayHide?.()
  getCalendarListAll()
}
const editScheduleClick_scheduleDetail = (val, type?) => {
  diaType.value = 'edit'
  nextTick(() => {
    createDateEventRef.value.openDialog(val, type)
  })
}
const ScheduleDetail_refresh = () => {
  updateEventList()
}


const fixedTaskClick = (taskName: string) => {
  selectedFixedTask.value = taskName
  selectedTaskIndex.value = null // 清除动态任务项的选中状态
  let path = `${route.path}?type=${selectedFixedTask.value}`
  router.push(path)
}
// 获取日历中的时间
const calculateStartEndDates = () => {
  let calendarApi = fullCalendar.value.getApi()
  let displayedDate = new Date(calendarApi.currentData.currentDate)
  let start, end
  switch (currentView.value) {
    case "dayGridMonth":
    case "listMonth":
      let month = displayedDate.getMonth() // 当前月份
      let year = displayedDate.getFullYear() // 当前年份
      start = new Date(year, month, 1) // 当月的第一天
      end = new Date(year, month + 1, 0) // 当月的最后一天
      break
    case "timeGridDay":
      let month1 = displayedDate.getMonth() // 当前月份
      let year1 = displayedDate.getFullYear() // 当前年份
      start = new Date(year1, month1, 1) // 当月的第一天
      end = new Date(year1, month1 + 1, 0) // 当月的最后一天
      break
    default:
      break
  }
  let startDate = `${start.getFullYear()}-${(start.getMonth() + 1).toString().padStart(2, "0")}-${start
    .getDate()
    .toString()
    .padStart(2, "0")} 00:00:00`
  let endDate = `${end.getFullYear()}-${(end.getMonth() + 1).toString().padStart(2, "0")}-${end.getDate().toString().padStart(2, "0")} 23:59:59`
  return { startDate, endDate }
}


// 日程列表
const confirm_createSchedule = async (val, id) => {
  updateEventList()
  if (val == 'detail') {
    ScheduleDetailRefs.value.getDetail(id)
  }
}
// 更新日程数据
const updateEventList = async () => {
  let { startDate, endDate } = calculateStartEndDates()
  const res = await sysCalendarQueryInterval({
    startDate,
    endDate,
    type: selectedFixedTask.value == null ? "schedule" : selectedFixedTask.value,
    scheduleId: selectedTaskIndex.value == null ? '' : selectedTaskIndex.value,
  })
  if (res.code == 200) {
    calendarOptions.events = res.data.map((item: any) => {
      return {
        title: item.label,
        start: item.startDate,
        end: item.endDate,
        color: item.calendarColor,
        content: item.content,
        id: item.id ? item.id : item.myTaskId,
        userList: item.userList,
        category: item.category,
        projectId: item.projectId
      }
    })
  }
}
// 新建日历
const openAddDia = () => {
  if (addCalendarDiaRef.value) {
    popoverRef.value.hide()
    addCalendarDiaRef.value.openDialog()
  }
}

// 选择人员
const openUserDia = () => {
  if (selectUserRef.value) {
    const clonedList = JSON.parse(JSON.stringify(peopleFollowList.value))
    selectUserRef.value.openDialogTransfer(clonedList)
  }
}
// 确认人员
const sureDialogTransferClick = (data: any) => {
  addpeopleFollow(data)
}
// 添加成员
const addpeopleFollow = async (data: any) => {
  let ids = data.map((item: any) => item.userId)
  const res = await apiSysScheduleAddAttention({
    attentionUserIdList: ids
  })
  if (res.code == 200) {
    ElMessage.success('添加成功')
    getPeopleFollow()
  }
}
// 获取成员列表
const getPeopleFollow = async () => {
  let res = await apiSysScheduleGetAttentionAll()
  if (res.code == 200) {
    peopleFollowList.value = res.data.map((item: any) => {
      return {
        ...item,
        typeId: item.id
      }
    })
  }
}
// 全选人员
const handleCheckAllPeopleChange = (val: any) => {
  let ids = peopleFollowList.value.map((item: any) => item.userId)
  checkedPeopleList.value = val ? ids : []
  isIndeterminatePeople.value = false
  let path = `${route.path}?people=1`
  router.push(path)
  getPeopleSchedule()
}
// 人员选择
const handleCheckedPeopleChange = (value: any) => {
  let checkedCount = value.length
  checkAllPeople.value = checkedCount === peopleFollowList.value.length
  isIndeterminatePeople.value = checkedCount > 0 && checkedCount < peopleFollowList.value.length
  let path = `${route.path}?people=1`
  router.push(path)
  getPeopleSchedule()
}
// 删除人员
const deletePeopleFollow = async (item: any) => {
  const res = await apiSysScheduleDeleteAttention({
    attentionUserId: item.userId
  })
  if (res.code == 200) {
    ElMessage.success('删除成功')
    getPeopleFollow()
  }
}
const getPeopleSchedule = async () => {
  checkedResourceList.value = []
  isIndeterminateResource.value = false
  checkAllResource.value = false
  let { startDate, endDate } = calculateStartEndDates()
  if (checkedPeopleList.value.length != 0) {
    apiSysScheduleAttentionShow({
      startDate,
      endDate,
      userIds: checkedPeopleList.value
    }).then((res: any) => {
      if (res.code == 200) {
        calendarOptions.events = res.data.map((item: any) => {
          return {
            title: item.label,
            start: item.startDate,
            end: item.endDate,
            color: item.calendarColor,
            content: item.content,
            id: item.id ? item.id : item.myTaskId,
            userList: item.userList,
            category: item.category,
            projectId: item.projectId
          }
        })
      } else {
        calendarOptions.events = []
      }
    })
  }
}
// 点击日历
const taskClick = (item: any) => {
  selectedTaskIndex.value = item.id
  selectedFixedTask.value = null
  let path = `${route.path}?scheduleId=${selectedTaskIndex.value}`
  router.push(path)
  updateEventList()
}
// 关注
const itemClick = async (item: any) => {
  if (item.check == "true") {
    await starClick(item.id)
    await getCalendarListAll()
  } else {
    const res = await sysScheduleAttentionAdd({
      scheduleId: item.id
    })
    if (res.code == 200) {
      await getCalendarListAll()
      await getCalendarList()

    }
  }

}
// 取消关注
const starClick = async (id: any) => {
  const res = await sysScheduleCancelAttentionDel(id)
  if (res.code === 200) {
    getCalendarList()
  }
}
// 高级设置
const deleteCalendar = (data: any) => {
  localStorage.setItem("scheduleData", JSON.stringify(data))
  router.push('/calendar/index/setting')
}
// 基础信息
const editClick = (data: any) => {
  localStorage.setItem("scheduleData", JSON.stringify(data))
  router.push('/calendar/index/info')
}
// 日历成员
const userClick = (data: any) => {
  localStorage.setItem("scheduleData", JSON.stringify(data))
  router.push('/calendar/index/calendarUsers')
}

// 获取关注日历列表
const getCalendarList = async () => {
  const res = await sysScheduleGetPersonalAttention()
  if (res.code === 200) {
    popoverData.value = res.data
  }
}
// 日历列表（全部）
const getCalendarListAll = async () => {
  const res = await sysScheduleAll({
    scheduleName: searchValue.value
  })
  if (res.code == 200) {
    calendarList.value = res.data

  }
}

onMounted(() => {
  getCalendarList()
  calculateStartEndDates()
  updateEventList()
  getPeopleFollow()
  getResourceAll()
  getResourceFollow()
  // getCalendarListAll()
})
</script>

<style lang="scss">
.calendar-popover {
  width: 200px !important;
  min-width: 200px !important;

  .calendar-list {
    padding-top: 10px;
    padding-bottom: 10px;

    .calendar-item {
      padding: 0px 10px;
      cursor: pointer;

      &:hover {
        background-color: #f5f5f5;
      }

      .item-box {
        height: 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .box-left {
          display: flex;
          align-items: center;

          div {
            max-width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          i {
            margin-right: 6px;
          }
        }
      }
    }
  }

  .add-btn {
    display: flex;
    border-top: 1px solid #e5e5e5;
    padding-top: 10px;
    cursor: pointer;
  }
}

.resourPopover {
  width: 200px !important;
  min-width: 200px !important;

  .popover-content {

    .lists {
      max-height: 300px;
      overflow-y: auto;

      .listsItem {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 40px;
        cursor: pointer;

        &:hover {
          background-color: #f5f5f5;
        }

        .leftItems {
          margin-left: 14px;
          display: flex;
          align-items: center;

          i {
            margin-right: 10px;
          }
        }

        .rightItems {
          margin-right: 14px;
        }

        .Name_box {
          display: inline-block;
          width: 120px;
          text-overflow: ellipsis;
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 1; //元素几行显示
          line-clamp: 1; //元素几行显示
          -webkit-box-orient: vertical;
        }
      }
    }
  }
}
</style>

<style lang="scss" scoped>
p {
  margin: 0px;
}

:deep(.el-dialog__header) {
  border-bottom: none !important;
}

:deep(.fc-addButton-button) {
  margin-left: 20px !important;
}

:deep(.fc-voiceButton-button) {
  margin-left: 20px !important;
}

:deep(.fc-header-toolbar) {
  font-size: 14px !important;
}

:deep(.fc-toolbar-chunk) {
  display: flex;
  align-items: center;

  .fc-next-button,
  .fc-prev-button {
    background: white !important;
    border: none;
    box-shadow: none !important;

    &:hover {
      color: #fff !important;
    }
  }

  .fc-icon-chevron-right,
  .fc-icon-chevron-left {
    color: #2c3e50;
  }
}

:deep(.fc-direction-ltr .fc-toolbar > * > :not(:first-child)) {
  margin: 0px;

}

:deep(.fc-toolbar-title) {
  margin: 0px 10px !important;
}

:deep(.custom-dropdown-item) {
  height: 40px;

  &:not(:first-child) {
    border-top: 1px solid #e5e5e5;
  }
}

/* start 日历头部修改按钮颜色 */
:deep(.fc-button-primary) {
  color: #fff !important;
  background-color: #6698ff !important;
  border-color: #6698ff !important;
  font-size: 14px !important;
}

:deep(.fc-button-primary:hover,
  .fc-button-primary:focus) {
  background: #88affc !important;
  border-color: #88affc !important;
  color: #fff !important;
}

:deep(.fc-button-primary:focus) {
  box-shadow: rgba(69, 149, 228, 0.5) 0px 0px 0px 0px !important;
}

:deep(.fc-button-primary:not(:disabled).fc-button-active) {
  background: #88affc !important;
  border-color: #88affc !important;
  color: #fff !important;
}

:deep(.fc-button-primary:not(:disabled).fc-button-active:focus,
  .fc-button-primary:not(:disabled):active) {
  box-shadow: rgba(69, 149, 228, 0.5) 0px 0px 0px 0px !important;
}

/**end */
.voice-item {
  position: relative;

  img {
    position: absolute;
    bottom: 4px;
    right: 14px;
  }

  // 语言录入动画-------------------start
  .voice_box {
    cursor: pointer;

    .SpeakType3 {
      width: 60px;
      font-size: 12px;
      color: #b3b0c3;
    }
  }

  .loaderRectangle {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 0 3px;
    position: absolute;
    bottom: 4px;
    right: 14px;
  }

  .loaderRectangle div {
    width: 4px;
    height: 8px;
    animation: 0.9s ease-in-out infinite;
    background: #3662ec;
    box-shadow: 0 0 20px rgba(18, 31, 53, 0.3);
  }

  .loaderRectangle div:nth-child(1) {
    animation-name: rectangleOneAnim;
    animation-delay: 1s;
  }

  @keyframes rectangleOneAnim {
    0% {
      height: 8px;
    }

    40% {
      height: 15px;
    }

    100% {
      height: 8px;
    }
  }

  .loaderRectangle div:nth-child(2) {
    animation-name: rectangleTwoAnim;
    animation-delay: 1.1s;
  }

  @keyframes rectangleTwoAnim {
    0% {
      height: 8px;
    }

    40% {
      height: 20px;
    }

    100% {
      height: 8px;
    }
  }

  .loaderRectangle div:nth-child(3) {
    animation-name: rectangleThreeAnim;
    animation-delay: 1.2s;
  }

  @keyframes rectangleThreeAnim {
    0% {
      height: 8px;
    }

    40% {
      height: 25px;
    }

    100% {
      height: 8px;
    }
  }

  .loaderRectangle div:nth-child(4) {
    animation-name: rectangleFourAnim;
    animation-delay: 1.3s;
  }

  @keyframes rectangleFourAnim {
    0% {
      height: 8px;
    }

    40% {
      height: 20px;
    }

    100% {
      height: 8px;
    }
  }

  .loaderRectangle div:nth-child(5) {
    animation-name: rectangleFiveAnim;
    animation-delay: 1.4s;
  }

  @keyframes rectangleFiveAnim {
    0% {
      height: 8px;
    }

    40% {
      height: 15px;
    }

    100% {
      height: 8px;
    }
  }

  // 语言录入动画-------------------end
}

.calendar-container {
  width: 100%;
  height: calc(100vh - 50px);
  display: flex;
  // margin: 20px;

  .left {
    width: 240px;

    // padding: 10px;
    .small-calendar {
      padding-left: 10px;
      padding-top: 10px;
    }

    // background: skyblue;
    .calendar-add {
      margin-top: 20px;
      border-top: 1px solid #e8e8e8;

      .add-top {
        height: 48px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;

        p {
          font-size: 14px;
          color: #999;
        }

        i {
          cursor: pointer;
          color: #999;
        }
      }



      .calendarItem_body {
        // height: 200px;
        max-height: 200px;
        overflow: hidden;
        overflow-y: auto;

        // margin: 0px -10px;


        .taskItem {
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          cursor: pointer;

          .taskLeft {
            display: flex;
            align-items: center;
            padding-left: 10px;

            .text_ellipsis {
              display: inline-block;
              width: 130px;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
          }

          &:hover {
            background-color: #f5f5f5;

            .taskRight {
              opacity: 1;
              display: flex;
            }
          }

          i {
            margin-right: 8px;
            font-size: 16px;
            // margin-left: 10px;
            margin-right: 10px;
          }

          .taskRight {
            opacity: 0;
            display: flex;
            /* 默认情况下，.taskRight 不可见 */
            transition: opacity 0.3s ease;
          }
        }

        .selected-bg {
          background-color: rgba(102, 152, 255, 0.1);
          color: #6698ff;
        }
      }
    }

    .userItem {
      border-top: 1px solid #e8e8e8;
      margin-top: 10px;

      .userItem_header {
        height: 48px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #999;
        font-size: 14px;
        padding: 10px;

        i {
          font-size: 18px;
          cursor: pointer;
        }
      }

      .userItem_content {
        max-height: 120px;
        overflow: hidden;
        overflow-y: auto;

        .userItem_body {
          // margin: 0px -10px;

          .userItem_body_box {
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 14px;
            cursor: pointer;

            .taskLeft {
              display: flex;
              align-items: center;
              padding-left: 10px;

              .text_ellipsis {
                display: inline-block;
                width: 120px;

                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
              }
            }

            &:hover {
              background-color: #f5f5f5;

              .taskRight {
                opacity: 1;
                display: flex;
              }
            }

            i {
              margin-right: 8px;
              font-size: 16px;
              // margin-left: 10px;
              margin-right: 10px;
            }

            .taskRight {
              opacity: 0;
              /* 默认情况下，.taskRight 不可见 */
              transition: opacity 0.3s ease;
            }
          }

          .userName {
            position: relative;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            font-size: 10px;
            line-height: 22px;
            background-color: #6698ff;
            text-align: center;
            color: white;
            margin-right: 10px;
          }
        }
      }


    }

    .resourceItem {
      border-top: 1px solid #e8e8e8;
      margin-top: 10px;

      .resourceItem_header {
        height: 48px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #999;
        padding: 10px;

        div {
          font-size: 14px;
        }

        i {
          font-size: 18px;
          cursor: pointer;
        }
      }

      .resourceItem_content {
        max-height: 80px;
        overflow: hidden;
        overflow-y: auto;

        .resourceItem_body {
          .taskItem {
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 14px;
            cursor: pointer;

            .taskLeft {
              padding-left: 10px;
              display: flex;
              align-items: center;
            }

            &:hover {
              background-color: #f5f5f5;

              .taskRight {
                opacity: 1;
              }
            }

            i {
              margin-right: 8px;
              font-size: 16px;
              // margin-left: 10px;
              margin-right: 10px;
            }

            .taskRight {
              opacity: 0;
              /* 默认情况下，.taskRight 不可见 */
              transition: opacity 0.3s ease;
            }
          }

          .selected-bg {
            background-color: rgba(102, 152, 255, 0.1);
            color: #6698ff;
          }
        }
      }


    }
  }

  .right {
    width: calc(100% - 240px);
    margin-top: 20px;
    margin-right: 20px;
  }
}
</style>